package com.example.jdbc0914.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ：lqs
 * @date ：Created in 2023/9/14 15:43
 * @description：
 * @modified By：
 * @version:
 */
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //什么资源允许放行。 login.jsp  /login
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        String path = req.getServletPath();
        if("/login.jsp".equals(path)||"/login".equals(path)){
            chain.doFilter(request,response);
            return; //结束方法
        }

        //如果登录过
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user!=null){
            chain.doFilter(request,response);
            return; //结束方法
        }
        //重定向到登录页面
        resp.sendRedirect("/login.jsp");
    }

    @Override
    public void destroy() {

    }
}
